<?php
//数据库操作类：自定义单表信息操作类
class Model
{
    //成员属性
    protected $link = null;    //数据库连接资源
    protected $tabName = null; //表名
    protected $pk = "id";      //主键名
    protected $fields = [];  //表字段信息
    protected $where = []; //封装搜索条件
    protected $order = null; //封装排序条件  
    protected $limit = null; //封装分页条件    
    
    //构造方法，实现数据库连接，表名初始化
    public function __construct($tabName)
    {
        $this->tabName = $tabName;
        $this->link = @mysqli_connect(HOST,USER,PASS,DBNAME) or die("数据库连接失败！");
        $this->link->query("SET NAMES utf8");
        $this->findFields(); //调用自定义方法来满足表字段信息封装
    }
    
    //加载当前表的字段信息
    private function findFields()
    {
        $sql = "desc {$this->tabName}";
        $result = mysqli_query($this->link,$sql);
        while($row = mysqli_fetch_assoc($result)){
            $this->fields[] = $row['Field']; //获取并封装当前字段信息
            if($row['Key']=="PRI"){
                $this->pk = $row['Field']; //获取主键
            }
        }
        mysqli_free_result($result);
    }
    
    //获取所有信息的方法
    public function findAll()
    {
        $res = [];
        $sql = "select * from {$this->tabName}";
        $result = mysqli_query($this->link,$sql);
        while($row = mysqli_fetch_assoc($result)){
            $res[] = $row;
        }
        mysqli_free_result($result);
        return $res;
    }
    
    //获取所有信息的方法
    public function select()
    {
        $res = [];
        $sql = "select * from {$this->tabName}";
        
        //判断并封装各种条件
        if(count($this->where)>0){
            $sql.=" where ".implode(" and ",$this->where);
        }
        if(!empty($this->order)){
            $sql .=" order by ".$this->order;
        }
        if(!empty($this->limit)){
            $sql .=" limit ".$this->limit;
        }
        //echo $sql;
        $result = mysqli_query($this->link,$sql);
        //echo $sql;
        while($row = mysqli_fetch_assoc($result)){
            $res[] = $row;
        }
        mysqli_free_result($result);
        //清楚搜索和排序条件
        $this->where = []; //搜索条件
        $this->order = null; //封装排序条件  
        $this->limit = null; //封装分页条件
        return $res;
    }
    
    //统计数据条数
    public function count()
    {
        $sql = "select count(*) num from {$this->tabName}";
        //判断并封装各种条件
        if(count($this->where)>0){
            $sql.=" where ".implode(" and ",$this->where);
        }        
        $result = mysqli_query($this->link,$sql);
        $row = mysqli_fetch_assoc($result);
        return $row['num'];
    }
    
    //获取单条数据信息方法（详请信息）
    public function find($id)
    {
        $sql = "select * from {$this->tabName} where {$this->pk}={$id}";
        $result = mysqli_query($this->link,$sql);
        if(mysqli_num_rows($result)>0){
            return mysqli_fetch_assoc($result);
        }
        return null;
    }
    
    //执行删除信息方法
    public function del($id=0)
    {
        $sql = "delete from {$this->tabName} where {$this->pk}={$id}";
        mysqli_query($this->link,$sql);
        return mysqli_affected_rows($this->link); //返回影响行数
    }
    
    //执行添加操作
    public function insert($data=array())
    {   
        if(empty($data)){
            $data = $_POST;
        }
           
        //过滤，判断并封装添加信息
        $fieldlist = [];
        $valuelist = [];
        foreach($data as $k=>$v){
            //判断是否是有效字段信息
            if(in_array($k,$this->fields)){
                $fieldlist[] = $k;  
                $valuelist[] = "'".$v."'";
            }
        }
        //拼装sql语句
        $sql = "insert into {$this->tabName}(".implode(",",$fieldlist).") values(".implode(",",$valuelist).")";
        //echo $sql;
        //执行
        mysqli_query($this->link,$sql);
        
        return mysqli_insert_id($this->link);
    }
    
    //执行修改操作
    public function update($data=array())
    {   
        if(empty($data)){
            $data = $_POST;
        }
           
        //过滤，判断并封装要修改的信息
        $valuelist = [];
        foreach($data as $k=>$v){
            //判断是否是有效字段信息，并且不是主键
            if(in_array($k,$this->fields) && $k!=$this->pk){
                $valuelist[] = $k."='".$v."'";
            }
        }
        //拼装sql语句
        $sql = "update {$this->tabName} set ".implode(",",$valuelist)." where {$this->pk}='{$data[$this->pk]}'";
        //echo $sql;
        //执行
        mysqli_query($this->link,$sql);
        //返回影响的行数
        return mysqli_affected_rows($this->link);
    }
    
    //封装搜素条件
    public function where($where)
    {
        $this->where[] = $where;
        return $this;
    }
    
    //封装排序条件
    public function order($order)
    {
        $this->order = $order;
        return $this;
    }
    
    //封装分页条件
    public function limit($m,$n=0)
    {
        if($n>0){
            $this->limit = "{$m},{$n}";
        }else{
            $this->limit = $m;
        }
        return $this;
    }
    
    //析构方法
    public function __destruct()
    {
        if($this->link){
            mysqli_close($this->link);
           // echo "数据连接被关闭";
        }
    }
    
}